<!-- 在线考试 -->
<template>
  <el-dialog title="在线考试" fullscreen :visible.sync="dialogVisible" width="80%" :show-close="false">
    <div style="
        display: flex;
        flex-direction: column;
      ">
      <el-row>
        <el-col>
          <div class="card-title">
            <!-- 添加倒计时 -->
            <div class="countdown">
              剩余时间: {{ countdown }} 秒
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <!-- 左侧答题卡 -->
        <el-col :span="6" :xs="24" :sm="6"
          style="position: fixed; top: 50px; left: 0; height: 100vh; overflow-y: auto;">
          <div class="card-contion">
            <div class="answer-card" v-if="radioList && radioList.length > 0">
              <div>
                <h1>单选题</h1>
              </div>
              <div class="grid">
                <div v-for="(item, index) in radioList.length" :key="index" class="question-button"
                  :class="{ 'active': isRadioAnswered(index) }" @click="scrollToQuestion1(index)">
                  {{ index + 1 }}
                </div>
              </div>
            </div>
            <div class="answer-card" v-if="judgmentList && judgmentList.length > 0">
              <div>
                <h1>判断题</h1>
              </div>
              <div class="grid">
                <div v-for="(item, index) in judgmentList.length" :key="index" class="question-button"
                  :class="{ 'active': isJudgmentAnswered(index) }" @click="scrollToQuestion2(index)">
                  {{ index + 1 }}
                </div>
              </div>
            </div>
            <div class="answer-card" v-if="multipleList && multipleList.length > 0">
              <div>
                <h1>多选题</h1>
              </div>
              <div class="grid">
                <div v-for="(item, index) in multipleList.length" :key="index" class="question-button"
                  :class="{ 'active': isMultipleAnswered(index) }" @click="scrollToQuestion3(index)">
                  {{ index + 1 }}
                </div>
              </div>
            </div>
            <div class="submit" style="">
              <div class="submit-button-1">
                <el-button type="primary" @click="submitPaper">交卷</el-button>
              </div>
              <!-- <div class="submit-button-2">
                <el-button type="warning" @click="submitPaper">结束考试</el-button>
              </div> -->
            </div>
          </div>
        </el-col>
        <!--右侧题目-->
        <el-col :span="16" :xs="24" :sm="16" :offset="6">
          <div class="question-container">
            <div v-if="radioList && radioList.length > 0">
              <el-divider content-position="left"><el-tag>单选题</el-tag></el-divider>
              <div :ref="'question1' + index" v-for="(item, index) in radioList" :key="item.questionId">
                <div>
                  <p class="question-name">{{ index + 1 }}. {{ item.questionName }}</p>
                </div>
                <div v-for="(item2, index2) in item.questionAnswerList" :key="index2">
                  <el-radio-group v-model="radioValue[index]"
                    @change="radioChange1(item.questionId, radioValue[index], index)">
                    <div style="margin-top: 10px; width: 100%">
                      <el-radio :label="item2.questionAnswerOption" border>{{ item2.questionAnswerOption }}.{{
                        item2.questionAnswerName
                      }}</el-radio>
                    </div>
                  </el-radio-group>
                </div>
              </div>
            </div>
            <div v-if="judgmentList && judgmentList.length > 0">
              <el-divider content-position="left"><el-tag>判断题</el-tag></el-divider>
              <div :ref="'question2' + index" v-for="(item, index) in judgmentList" :key="item.questionId">
                <div>
                  <p class="question-name">{{ index + 1 }}. {{ item.questionName }}</p>
                </div>
                <div v-for="(item2, index2) in item.questionAnswerList" :key="index2">
                  <el-radio-group v-model="judgmentValue[index]" @change="
                    radioChange2(item.questionId, judgmentValue[index], index)
                    ">
                    <div style="margin-top: 10px">
                      <el-radio :label="item2.questionAnswerOption" border>{{ item2.questionAnswerOption }}.{{
                        item2.questionAnswerName
                      }}</el-radio>
                    </div>
                  </el-radio-group>
                </div>
              </div>
            </div>

            <div v-if="multipleList && multipleList.length > 0">
              <el-divider content-position="left"><el-tag>多选题</el-tag></el-divider>
              <div v-for="(item, index) in multipleList" :key="item.questionId">
                <div>
                  <p class="question-name">{{ index + 1 }}. {{ item.questionName }}</p>
                </div>
                <el-checkbox-group v-model="multiValue[index]" size="small"
                  @change="checkboxChange(item.questionId, multiValue[index], index)">
                  <div v-for="(item2, index2) in item.questionAnswerList" :key="index2" style="margin-top: 10px">
                    <el-checkbox :label="item2.questionAnswerOption" border>
                      {{ item2.questionAnswerOption }}. {{ item2.questionAnswerName }}
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </div>
            <div v-if="fillList && fillList.length > 0">
              <el-divider content-position="left"><el-tag>填空题</el-tag></el-divider>
              <div v-for="item in radioList" :key="item.questionId">
                <div>
                  <p class="question-name">{{ item.questionName }}</p>
                </div>

                <div v-for="item2 in item.questionAnswerList" :key="item2.questionAnswerId">
                  <p>{{ item2.questionAnswerOption + item2.questionAnswerName }}</p>
                </div>
              </div>
            </div>
            <div v-if="shortList && shortList.length > 0">
              <el-divider content-position="left"><el-tag>简答题</el-tag></el-divider>
              <div v-for="item in radioList" :key="item.questionId">
                <div>
                  <p>{{ item.questionName }}</p>
                </div>

                <div v-for="item2 in item.questionAnswerList" :key="item2.questionAnswerId">
                  <p>{{ item2.questionAnswerOption + item2.questionAnswerName }}</p>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <PaperResult ref="PaperResultRef"></PaperResult>
  </el-dialog>
</template>
<script>
import {
  paperMarking,
} from "@/api/train/index.js";

import { getQuestionListByExaminationPlanId } from "@/api/train/index.js"
import PaperResult from "./PaperResult.vue";
export default {
  components: {
    PaperResult,
  },
  data() {
    return {
      countdown: 30 * 60, // 设置倒计时初始值为300秒（5分钟）
      countdownInterval: null, // 存储倒计时的定时器ID
      totalQuestions: 20, // 总题数
      radioAnsweredQuestions: [], // 单选题已答题目索引
      multiAnsweredQuestions: [], // 多选题已答题目索引
      judgmentAnsweredQuestions: [], // 判断题已答题目索引
      dialogVisible: false,
      // 单选题的值
      radioValue: [],
      //判断题的值
      judgmentValue: [],
      //多选选定值
      multiValue: [],
      //填空的值
      fillValue: [],
      //简答题的值
      shortValue: [],
      //总题数
      totalQu: 0,

      //已答列表
      radionAnsweredList: [],
      judgmentAnsweredList: [],
      multiAnsweredList: [],
      //回显的题目
      radioList: [],
      multipleList: [],
      judgmentList: [],
      fillList: [],
      shortList: [],

      examinationPlanName: "",
      examinationPlanId: 0,
    };
  },
  created() {
    this.startCountdown();
  },
  mounted() {

  },
  methods: {
    scrollToQuestion1(index) {
      const questionRef = this.$refs['question1' + index];
      if (questionRef && questionRef.length > 0) {
        questionRef[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    },
    scrollToQuestion2(index) {
      const questionRef = this.$refs['question2' + index];
      if (questionRef && questionRef.length > 0) {
        questionRef[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    },
    scrollToQuestion3(index) {
      const questionRef = this.$refs['question3' + index];
      if (questionRef && questionRef.length > 0) {
        questionRef[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    },
    startCountdown() {
      this.countdownInterval = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.countdownInterval);
          this.submitPaper(); // 时间到自动提交试卷
        }
      }, 1000);
    },
    //单选框的答题卡回显
    isRadioAnswered(index) {
      return this.radioAnsweredQuestions.includes(index);
    },
    //判断题的答题卡回显
    isJudgmentAnswered(index) {
      return this.judgmentAnsweredQuestions.includes(index);
    },
    //多选题的答题卡回显
    isMultipleAnswered(index) {
      return this.multiAnsweredQuestions.includes(index);
    },
    selectQuestion(index) {
      // 选择题目逻辑
      if (!this.isAnswered(index)) {
        this.answeredQuestions.push(index);
      }
      // 这里可以添加逻辑跳转到对应题目
    },

    //单选框
    radioChange1(questionId, value, index) {
      let obj = {
        questionId: questionId,
        chooseAnswer: value,
      };
      this.radionAnsweredList[index] = obj;

      // 添加已回答的题目索引
      if (!this.radioAnsweredQuestions.includes(index)) {
        this.radioAnsweredQuestions.push(index);
      }
    },
    radioChange2(questionId, value, index) {
      let obj = {
        questionId: questionId,
        chooseAnswer: value,
      };
      this.judgmentAnsweredList[index] = obj;
      //添加到判断题的已答列表
      if (!this.judgmentAnsweredQuestions.includes(index)) {
        this.judgmentAnsweredQuestions.push(index);
      }
    },

    //多选框的值
    checkboxChange(questionId, selectedValues, index) {
      // 对选中的值进行排序
      const sortedValues = selectedValues.sort(); // 按字母顺序排序
      // 更新 multiAnsweredList，使用选中的值
      this.multiAnsweredList[index] = {
        questionId: questionId,
        chooseAnswer: sortedValues.join('') // 将选中的答案连接成字符串
      };
      // 添加已回答的题目索引
      if (!this.multiAnsweredQuestions.includes(index)) {
        this.multiAnsweredQuestions.push(index);
      }
    },



    //回显试卷
    show(row) {
      this.examinationPlanName = row.examinationPlanName;
      this.dialogVisible = true;
      this.examinationPlanId = row.examinationPlanId;
      this.countdown = row.testDuration * 60;
      getQuestionListByExaminationPlanId({
        examinationPlanId: row.examinationPlanId,
      }).then((res) => {
        console.log(res);
        this.radioList = res.data.radioList;
        this.multipleList = res.data.multipleList;
        this.multiValue = Array(this.multipleList.length).fill([]); // Initialize with empty arrays
        this.judgmentList = res.data.judgmentList;
        this.fillList = res.data.fillList;
        this.shortList = res.data.shortList;
        this.totalQuestions = this.radioList.length + this.multipleList.length + this.judgmentList.length + this.fillList.length + this.shortList.length;
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.clearValue();
      clearInterval(this.countdownInterval);
    },

    //交卷
    submitPaper() {
      // 检查答题卡是否全部作答
      const completeAnswers = [];

      // Process radio questions
      this.radioList.forEach((item, index) => {
        const answer = this.radioAnsweredQuestions.includes(index)
          ? this.radionAnsweredList[index]
          : { questionId: item.questionId, chooseAnswer: '无' };
        completeAnswers.push(answer);
      });

      // Process judgment questions
      this.judgmentList.forEach((item, index) => {
        const answer = this.judgmentAnsweredQuestions.includes(index)
          ? this.judgmentAnsweredList[index]
          : { questionId: item.questionId, chooseAnswer: '无' };
        completeAnswers.push(answer);
      });

      // Process multiple choice questions
      this.multipleList.forEach((item, index) => {
        const answer = this.multiAnsweredList[index] // 从 multiAnsweredList 获取答案
          ? this.multiAnsweredList[index] // 如果存在，使用它
          : { questionId: item.questionId, chooseAnswer: '无' }; // 如果没有选择，默认使用 '无'

        completeAnswers.push(answer);
      });

      // Check if there are unanswered questions
      const totalAnswered = this.radioAnsweredQuestions.length + this.judgmentAnsweredQuestions.length + this.multiAnsweredQuestions.length;
      const totalQuestions = this.radioList.length + this.judgmentList.length + this.multipleList.length;

      if (totalAnswered < totalQuestions) {
        this.$confirm('您还有未作答的题目，确认要提交吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitAnswers(completeAnswers);
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交'
          });
        });
      } else {
        this.submitAnswers(completeAnswers);
      }
    },

    submitAnswers(completeAnswers) {
      let params = {
        examinationPlanId: this.examinationPlanId,
        answerStr: JSON.stringify(completeAnswers),
        isSimulate: 2, //正式考试
      };

      paperMarking(params).then((res) => {
        console.log(res);
        if (res.code == 200) {
          //关闭答题页面，展示结果页面
          this.dialogVisible = false;
          this.clearValue();
          this.$refs.PaperResultRef.show(res.data.trainRecordId, 2);
        }
      });
    },
    clearValue() {
      this.newResultArr = []; // 清空结果数组
      this.radioValue = []; // 清空单选题的选择
      this.judgmentValue = []; // 清空判断题的选择
      this.multiValue = []; // 清空多选题的选择
      this.multiAnsweredList = []; // 清空多选题的回答列表
      this.judgmentAnsweredList = []; // 清空判断题的回答列表
      this.radionAnsweredList = []; // 清空单选题的回答列表
      this.fillList = []; // 清空填空题的选择（如果有）
      this.shortList = []; // 清空简答题的选择（如果有）
      // 其他需要清空的状态可以在这里添加
    }
  },
};
</script>
<style lang="scss" scope>
@import "../css/FormalExamin.scss";
</style>
